import json
import aiohttp
from fastapi import UploadFile
from typing import Dict

async def send_async_request(url, headers, data):
    async with aiohttp.ClientSession() as session:
        async with session.post(url, headers=headers, json=data) as response:
            if response.status == 200:
                async for chunk in response.content.iter_chunks():
                    if chunk[0]:
                        try:
                            chunk_data = json.loads(chunk[0].decode('utf-8'))
                            yield chunk_data
                        except json.JSONDecodeError:
                            print("响应数据不是有效的JSON格式")
            else:
                print(f"请求失败，状态码: {response.status}")
                print(await response.text())
                yield None

async def send_async_rag_request(url: str, headers: Dict[str, str], file: UploadFile):
    async with aiohttp.ClientSession() as session:
        # 构造 multipart/form-data 请求
        form_data = aiohttp.FormData()
        form_data.add_field(
            "file",  # 字段名，必须与接口参数名一致
            file.file,  # 文件对象
            filename=file.filename,  # 文件名
            content_type=file.content_type  # 文件类型
        )

        # 发送异步请求
        async with session.post(url, headers=headers, data=form_data) as response:
            return await response.json()
